﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Server.API.Application.Command.Goods;
using Yitter.IdGenerator;

namespace Server.API.Application.Handler.Goods
{
    public class AddGoodsHandler : IRequestHandler<AddGoodsCommand, APIResult<int>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly ILogger<AddGoodsHandler> log;
        private readonly IMapper mapper;

        public AddGoodsHandler(IRepository<GoodsModel> goodsway, ILogger<AddGoodsHandler> log, IMapper mapper)
        {
            this.goodsway = goodsway;
            this.log = log;
            this.mapper = mapper;
        }
        /// <summary>
        ///商品添加    
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        public async Task<APIResult<int>> Handle(AddGoodsCommand request, CancellationToken cancellationToken)
        {
            var value = mapper.Map<GoodsModel>(request); //映射
            value.Id = YitIdHelper.NextId();  // 雪花ID
            var number = 0;
            if (!string.IsNullOrEmpty(request.GoodsName))
            {
                number += 20;
            }
            if (!string.IsNullOrEmpty(request.Companyname))
            {
                number += 20;
            }
            if (request.Expired != null)
            {
                number += 20;
            }
            if (!string.IsNullOrEmpty(request.Cover))
            {
                number += 20;
            }
            if (!string.IsNullOrEmpty(request.Check))
            {
                number += 20;
            }
            value.Finiststate = number.ToString() + "%";  // 商品数据完成度
            var result = await goodsway.Addway(value);  
       

            if (result > 0)
            {
                log.LogInformation("商品添加成功");
                return new APIResult<int>()
                {
                    Num = StateCode.OK,
                    Message = "添加成功",
                    Data = result
                };

                //var list = goodsway.GetAll().Where(x => x.Order == request.Order);  //重复添加
                //if (list.Any())
                //{
                //    log.LogInformation("订单号已存在,不能重复添加");
                //    return new APIResult<int>()
                //    {
                //        Num = StateCode.Fail,
                //        Message = "订单号已存在,不能重复添加",
                //    };
                //}

            }
            else
            {
                log.LogError("添加失败");
                return new APIResult<int>()
                {
                    Num = StateCode.Fail,
                    Message = "添加失败",
                };
            }

        }
    }
}
